package cn.intozhou.zlive.utils;

import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public final class DbManager {

	private static DbManager dbManager;
	
	
	
	
	private java.sql.Connection conn;
	
	private DbManager() {
	}
	
	public static DbManager getInstance() {
		if(dbManager == null) {
			dbManager = new DbManager();
		}
		
		return dbManager;
	}
	
	
	private void connectDb() throws SQLException{
		 String driveName = "jdbc:mysql://";
		 String host = "192.168.1.98";
		 String port = "30365";
		 String dbName = "b4c58fd3";
		 String user = "b4c58fd3";
		 String password = "08725f33";
		 
		 
		 String url = driveName + host + ":" + port + "/" + dbName;
		 conn = DriverManager.getConnection(url, user, password);
	}
	
	private void closeDb() throws SQLException {
		if(conn != null)
			conn.close();
		conn = null;
	}
	
	/**
	 * 执行插入、删除、更新语句
	 * @param sql
	 * @return 执行成功返回true，否则返回false
	 * @throws SQLException
	 */
	public boolean execute(String sql) throws SQLException {
		Statement statement = null;
		try {
			if(conn == null) {
				connectDb();
			}
			statement = conn.createStatement();
		    statement.execute(sql);
			return statement.getUpdateCount() > 0;
		}catch(SQLException e) {
			throw e;
		}finally {
			if(statement != null)
				statement.close();
			closeDb();
		}
	}
	
	
	/**
	 * 查询数据返回结果集
	 * @param sql 查询语句
	 * @return 结果集
	 * @throws SQLException
	 */
	public ResultSet query(String sql) throws SQLException {
		ResultSet set = null;
		Statement statement = null;
		try {
			statement = conn.createStatement();
			set = statement.executeQuery(sql);
		} catch (SQLException e) {
			throw e;
		} finally {
			if(statement != null)
				statement.close();
			closeDb();
		}
		return set;
	}
}
